﻿using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using UnityEngine.UI;
using Type = System.Type;
public class UIHelper : MonoBehaviour
{
    /// <summary>
    /// 是否点击了gui对象
    /// </summary>
    /// <param name="raycaster"></param>
    /// <returns></returns>
    public static bool IsRaycastGUIObjects(GraphicRaycaster raycaster)
    {
        PointerEventData eventData = new PointerEventData(EventSystem.current);
        eventData.pressPosition = Input.mousePosition;
        eventData.position = Input.mousePosition;

        List<RaycastResult> list = new List<RaycastResult>();
        raycaster.Raycast(eventData, list);
        //Debug.Log(list.Count);
        return list.Count > 0;
    }
    /// <summary>
    /// 界面专用方法，查找属性
    /// </summary>
    static public T FindProperty<T>(Transform root, string path, Dictionary<string, Transform> caches, Dictionary<string, string> alias)
        where T : Component
    {
        return FindProperty(typeof(T), root, path, caches, alias) as T;
    }

    static public Component FindProperty(Type t, Transform root, string path, Dictionary<string, Transform> caches, Dictionary<string, string> alias)
    {
        string[] arr = path.Split('/');
        int index = 0, count = arr.Length - 1;
        string prefix = root.GetInstanceID() + ":";
        for (; index < count; index++)
        {
            string key = prefix + arr[index] + "/";
            if (!caches.ContainsKey(key))
                break;
            root = caches[prefix = key];
        }

        for (; index <= count; index++)
        {
            bool find = false;
            string key = arr[index];
            foreach (Transform child in root)
            {
                if (child.name == key)
                {
                    root = child;
                    caches[prefix += (key + "/")] = child;
                    if (alias != null && alias.ContainsKey(key))
                    {
                        child.gameObject.name = alias[key];
                    }
                    find = true;
                    break;
                }
            }
            if (!find)
                return null;
        }
        return root.GetComponent(t);
    }

}
